#!/bin/bash

# 内存检测功能测试脚本
# 用途：验证进程内存监控功能是否正常工作

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "=========================================="
echo "Java进程内存检测功能测试"
echo "=========================================="

# 测试进程名
TEST_PROCESS="ali_fxtools_web01"

echo "1. 测试进程查找功能..."

# 使用与监控脚本相同的逻辑查找进程
ps_output=$(ps aux | grep -v grep | grep -w "$TEST_PROCESS" | head -1)

if [[ -n "$ps_output" ]]; then
    echo "✓ 找到进程: $TEST_PROCESS"
    echo "   进程信息: $ps_output"
    
    # 提取各个字段进行测试
    echo ""
    echo "2. 测试内存数据提取..."
    
    # 提取内存使用率（第4列）
    memory_percent=$(echo "$ps_output" | awk '{print $4}')
    echo "   原始内存数据: '$memory_percent'"
    
    # 清理数据
    cleaned_memory=$(echo "$memory_percent" | tr -cd '0-9.')
    echo "   清理后数据: '$cleaned_memory'"
    
    # 提取整数部分
    if [[ "$cleaned_memory" == *.* ]]; then
        memory_int=$(echo "$cleaned_memory" | cut -d. -f1)
    else
        memory_int="$cleaned_memory"
    fi
    echo "   提取整数: '$memory_int'"
    
    # 验证数字有效性
    if [[ "$memory_int" =~ ^[0-9]+$ ]] && [[ "$memory_int" -ge 0 ]] && [[ "$memory_int" -le 100 ]]; then
        echo "✓ 内存数据有效: ${memory_int}%"
    else
        echo "✗ 内存数据无效: '$memory_int'"
    fi
    
    echo ""
    echo "3. 测试数值比较功能..."
    
    # 测试不同的阈值
    test_thresholds=(50 85 90 95)
    
    for threshold in "${test_thresholds[@]}"; do
        if [[ "$memory_int" =~ ^[0-9]+$ ]] && [[ "$threshold" =~ ^[0-9]+$ ]]; then
            if [[ $memory_int -gt $threshold ]]; then
                echo "   内存${memory_int}% > 阈值${threshold}% : 需要重启"
            else
                echo "   内存${memory_int}% <= 阈值${threshold}% : 正常"
            fi
        else
            echo "   数据验证失败: 内存='$memory_int', 阈值='$threshold'"
        fi
    done
    
else
    echo "✗ 未找到进程: $TEST_PROCESS"
    echo ""
    echo "所有Java进程："
    ps aux | grep java | grep -v grep
fi

echo ""
echo "4. 测试完整监控脚本..."

if [[ -f "$SCRIPT_DIR/process_monitor.sh" ]]; then
    echo "运行监控脚本测试模式..."
    bash "$SCRIPT_DIR/process_monitor.sh" -t
else
    echo "✗ 监控脚本不存在: $SCRIPT_DIR/process_monitor.sh"
fi

echo ""
echo "=========================================="
echo "测试完成"
echo "==========================================" 
